<template>
  <g-table-page
    :store-model-name="storeModelName"
    add-btn-link="/admin/trophy/add"
    add-btn-link-text="添加奖杯"
    :selection="false"
    :table-operation="tableOperation"
    :show-dropdown-groups="true"
  >
    <!-- 根据tableHeadList slotName字端 动态插入 插槽 -->
    <template v-for="item in tableHeadListSlotName" :key="item.slotName" #[item.slotName]="{ row }">
      <div v-if="row">
        <template v-if="item.prop == 'rankNames'">
          <span v-for="(rk,index) in row['rankList']" :key="index">
            {{ rk.rankNameCn }}；
          </span>
        </template>
        <span v-if="item.prop == 'rankYear'">
          {{ formatYearQuarter(row['rankYear']) }}
        </span>
        <span v-if="item.prop == 'trophyStatus'">
          <!-- 1.未申请 2.已申请 3.待制作 4.待审核 5.已完成', -->
          <span v-if="row[item.prop] == 1">未申请</span>
          <span v-else-if="row[item.prop] == 2">已申请</span>
          <span v-else-if="row[item.prop] == 3">待制作</span>
          <span v-else-if="row[item.prop] == 4">待审核</span>
          <span v-else-if="row[item.prop] == 5">已完成</span>
        </span>
        <span v-if="item.prop == 'rankPublishDate'">
          {{ dayjs(row[item.prop]).format('YYYY-MM-DD') }}
        </span>
        <span v-if="item.prop == 'download' && row['trophyStatus'] == 5">
          <!-- 1.未下载 2.已下载 -->
          <span v-if="row[item.prop] == 1">未下载</span>
          <span v-else-if="row[item.prop] == 2">已下载</span>
        </span>
      </div>
    </template>
  </g-table-page>
  <!-- 申请 -->
  <g-dialog
    v-model:dialog-visible="applyVisible"
    title="申请奖杯"
    width="650px"
    save-btn-text="提交"
    :click-sure-btn="saveApplyInfoFunc"
  >
    <el-form
      ref="applyRuleForm"
      :model="applyFormData"
      :rules="applyFormRules"
      label-position="right"
      label-width="140px"
      inline
    >
      <el-form-item label="获奖机构名称：" prop="researchOrgName">
        <el-input
          v-model="applyFormData.id"
          type="hidden"
        />
        <el-input
          v-model="applyFormData.researchOrgName"
          type="text"
          clearable
          disabled
        />
      </el-form-item>
      <el-form-item label="申请说明：" prop="applyExplain">
        <el-input
          v-model="applyFormData.applyExplain"
          placeholder="请输入申请说明"
          :rows="4"
          type="textarea"
          clearable
        />
      </el-form-item>
      <el-form-item label="机构LOGO：" prop="logo">
        <el-upload
          class="avatar-uploader"
          :data="{orgId: orgId, fileType: 1, moduleType: 1}"
          :multiple="false"
          :action="UPLOAD"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
  </g-dialog>

  <!-- 其他操作 -->
  <g-dialog
    v-model:dialog-visible="otherOptVisible"
    :title="optTitle"
    width="680px"
    :show-cancel-btn="false"
  >
    <other-opt
      v-if="otherOptVisible"
      v-model:other-opt-visible="otherOptVisible"
      :opt-type="optType"
      :trophy="trophy"
    />
  </g-dialog>
</template>

<script setup lang="ts">
import { computed, toRefs, ref, reactive } from 'vue'
import type { TableHeadList } from '@/types/storeModule'
import router from '@/router'
import store from '@/store'
import { UPLOAD, DOWNLOAD_SINGLE } from '@/api/file'
import { updateTrophyApi, getTrophyByIdApi } from '@/api/admin'
import type { Loading } from '@/components/Dialog/types'
import { assign, omit, cloneDeep } from 'lodash-es'
import dayjs from 'dayjs'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'
import  { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import OtherOpt from './otherOpt.vue'

const roles = computed(() => store.state['user'].userInfo.roles)
// 1.系统管理员 2.设计师 3.调研管理员 4.访客
const roleId = roles.value[0]
// console.log('roleId---', roleId);
const storeModelName = 'trophyModule'
const orgId = ref<number>()
const proxyResoucePath = ref<string>()
const tableOperation = {
    width: 120,
    fixed: 'right',
    buttonGroups: [
        ({ row }) => {
            if(roleId === 4){
                if(row.trophyStatus === 1){
                    if(dayjs().diff(dayjs(row.rankPublishDate), 'month') <= 6){ // 距榜单发布半年内显示申请，可以操作
                        return {
                            name: '申请',
                            isShow: true,
                            click: ({ row }) => {
                                console.log('调研机构4--未申请1--申请（半年内）--可操作')
                                applyFormData = assign(applyFormData, { id: row.id, researchOrgName: row.researchOrgName })
                                orgId.value = row.researchOrgId
                                proxyResoucePath.value = row.researchOrgId
                                applyVisible.value = true
                            }
                        }
                    } else { // 距榜单发布超出半年显示未申请，并不可操作
                        return {
                            name: '未申请',
                            isShow: true,
                            type: 'info',
                            disabled: true,
                            click: ({ row }) => {
                                console.log('调研机构4--未申请1--未申请（半年外）--不可操作')
                            }
                        }
                    }
                }else if(row.trophyStatus === 2){
                    return {
                        name: '审核中',
                        isShow: true,
                        type: 'info',
                        disabled: true,
                        click: ({ row }) => {
                            console.log('调研机构4--已申请2--审核中--不可操作')
                            // if(showOrOpt.value.reviewOpt){
                            // }
                        }
                    }
                }else if(row.trophyStatus === 3){
                    return {
                        name: '制作中',
                        isShow: true,
                        type: 'info',
                        disabled: true,
                        click: ({ row }) => {
                            console.log('调研机构4--待制作3--制作中--不可操作')
                        }
                    }
                }else if(row.trophyStatus === 4){
                    return {
                        name: '制作中',
                        isShow: true,
                        type: 'info',
                        disabled: true,
                        click: ({ row }) => {
                            console.log('调研机构4--待审核4--制作中--不可操作')
                        }
                    }
                }else if(row.trophyStatus === 5){
                    return {
                        name: '下载电子奖杯',
                        isShow: true,
                        click: ({ row }) => {
                            console.log('调研机构4--已完成5--下载电子奖杯--可操作')
                            downFileFunc(row.id, row.trophyLinks)
                        }
                    }
                }else{
                    return {
                        name: '无权操作',
                        isShow: false
                    }
                }
            }else if(roleId === 2){
                if(row.trophyStatus === 3){
                    return {
                        name: '上传电子奖杯',
                        isShow: true,
                        click: ({ row }) => {
                            console.log('设计师2--待制作3--上传电子奖杯--可操作')
                            optTitle.value = '上传电子奖杯'
                            optType.value = 2
                            initTrophyFunc({ id: row.id })

                        }
                    }
                }else if(row.trophyStatus === 4){
                    return {
                        name: '下载电子奖杯',
                        isShow: true,
                        click: ({ row }) => {
                            console.log('设计师2--待审核4--下载电子奖杯--可操作')
                            downFileFunc(row.id, row.trophyLinks)
                        }
                    }
                }else if(row.trophyStatus === 5){
                    return {
                        name: '下载电子奖杯',
                        isShow: true,
                        click: ({ row }) => {
                            console.log('设计师2--已完成5--下载电子奖杯--可操作')
                            downFileFunc(row.id, row.trophyLinks)
                        }
                    }
                }else{
                    return {
                        name: '无权操作',
                        isShow: false
                    }
                }
            }else if(roleId === 3){
                if(row.trophyStatus === 1){
                    return {
                        name: '申请',
                        isShow: true,
                        click: ({ row }) => {
                            console.log('调研管理员3--未申请1--申请--可操作')
                            applyFormData.value = assign(applyFormData.value, { id: row.id, researchOrgName: row.researchOrgName })
                            orgId.value = row.researchOrgId
                            proxyResoucePath.value = row.researchOrgId
                            applyVisible.value = true
                        }
                    }
                }else if(row.trophyStatus === 2){
                    return {
                        name: '资料审核',
                        isShow: true,
                        click: ({ row }) => {
                            console.log('调研管理员3--已申请2--资料审核--可操作')
                            optTitle.value = '资料审核'
                            optType.value = 1
                            initTrophyFunc({ id: row.id })
                        }
                    }
                }else if(row.trophyStatus === 3){
                    return {
                        name: '制作中',
                        isShow: true,
                        type: 'info',
                        disabled: true,
                        click: ({ row }) => {
                            console.log('调研管理员3--待制作3--制作中--不可操作')
                        }
                    }
                }else if(row.trophyStatus === 4){
                    return {
                        name: '电子奖杯审核',
                        isShow: true,
                        click: ({ row }) => {
                            console.log('调研管理员3--待审核4--电子奖杯审核--可操作')
                            optTitle.value = '电子奖杯审核'
                            optType.value = 3
                            initTrophyFunc({ id: row.id })
                        }
                    }
                }else if(row.trophyStatus === 5){
                    return {
                        name: '下载电子奖杯',
                        isShow: true,
                        click: ({ row }) => {
                            console.log('调研管理员3--已完成5--下载电子奖杯--可操作')
                            downFileFunc(row.id, row.trophyLinks)
                        }
                    }
                }else{
                    return {
                        name: '无权操作',
                        isShow: false
                    }
                }
            }else{
                return {
                    name: '无权操作',
                    isShow: false
                }
            }
        },
        ({ row }) => {
            if(roleId === 3 && row.trophyStatus === 5 && row.download === 1){
                return {
                    name: '撤回奖杯',
                    isShow: true,
                    click: ({ row }) => {
                        console.log('调研管理员3--已完成5--撤回奖杯（未下载过）--可操作')
                        optTitle.value = '撤回奖杯'
                        optType.value = 4
                        initTrophyFunc({ id: row.id })
                    }
                }
            }else{
                return {
                    name: '无权操作',
                    isShow: false
                }
            }
        }
    ]
}

const tableHeadListSlotName = computed(() => {
    const tableHeadList = store.state[storeModelName].tableHeadList
    return tableHeadList.filter((item: TableHeadList) => item.slotName)
})
// 申请
const applyVisible = ref<boolean>(false)
let applyFormData = ref(<
  {
    id: number
    researchOrgName: string
    applyExplain: string
    logo: string
	trophyStatus: number
  }
>{
    id: 0,
    researchOrgName: '',
    applyExplain: '',
    logo: ''
})
const applyFormRules = reactive<FormRules>({
    applyExplain: [{ required: true, message: '请输入备注说明', trigger: 'change' }]
})
const applyRuleForm = ref<FormInstance>()
const saveApplyInfoFunc = (loading: Loading) => {
    applyRuleForm.value?.validate(async (valid: boolean): Promise<void> => {
        if (valid) {
            if(!applyFormData.value.logo){
                ElMessage.warning('请上传 LOGO')
                return
            }
            loading(true)
            // 流程状态标为已申请
            applyFormData.value.trophyStatus = 2
            updateTrophyApi(applyFormData.value).then((res) => {
                if(res*1 === 200)
                    ElMessage.success('申请成功')
            })
            setTimeout(() => {
                loading(false)
                router.go(0)
            }, 100)
        } else {
            return
        }
    })
}
const imageUrl = ref('')
const uploadLogoParams = ref<string>()
const handleAvatarSuccess: UploadProps['onSuccess'] = ( response, uploadFile) => {
    console.log('response----',response)
    console.log('uploadFile----',uploadFile)
    imageUrl.value = URL.createObjectURL(uploadFile.raw!)
    if(response.code === 200){
        applyFormData.value.logo = response.data.fileId
    }
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('请上传 JPG｜JPEG 格式的文件!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('请上传小于2M的图片!')
        return false
    }
    return true
}
// 其他操作
let otherOptVisible = ref<boolean>(false)
const optTitle = ref<string>('')
// optType 1=资料审核  2=上传电子奖杯 3=电子奖杯审核  4=撤回奖杯
const optType = ref<number>()
let trophy = ref<any>()
const initTrophyFunc = async (param) => {
    const data = await getTrophyByIdApi(param)
    trophy.value = omit(data, ['History', 'history', 'repeatKeys'])
    otherOptVisible.value = true
}
const downFileFunc = (id, filIds) => {
    location.href = DOWNLOAD_SINGLE + '?id=' + filIds
    // updateTrophyApi({id: id, download: 2}).then((res) => {
    //   if(res*1 === 200) {
    //     console.log('下载成功');
    //     router.go(0)
    //   }
    // })
}
const formatYearQuarter = (yearQuarter) => {
    let yearStr = (yearQuarter + '').substring(0,4), quarter = (yearQuarter + '').substring(4), labelStr = ''
    if(quarter === '01') labelStr = 'Q1'
    else if(quarter === '02') labelStr = 'Q2'
    else if(quarter === '04') labelStr = '排名'
    else if(quarter === '05') labelStr = 'Q4'
    return yearStr + labelStr
}
</script>
<style scoped>
  .avatar-uploader .avatar {
    width: 80px;
    height: 80px;
    display: block;
  }
</style>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    text-align: center;
  }
</style>
